package br.perfiman.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import br.perfiman.dao.AbstractDAOService;
import br.perfiman.dao.PortfolioDAOService;
import br.perfiman.model.Asset;
import br.perfiman.model.Portfolio;
import br.perfiman.model.Trade;
import br.perfiman.service.PortfolioService;
import br.perfiman.utils.BussinessUtils;

@Stateless
public class PortfolioServiceBean extends AbstractServiceBean<Portfolio> implements PortfolioService{
	@EJB
	protected PortfolioDAOService dao;
	
	@Override
	public AbstractDAOService<Portfolio> getDao() {
		return dao;
	}

	@Override
	public Portfolio insert(Portfolio entity) throws Exception {
		return super.insert(entity);
	}

	@Override
	public void remove(Portfolio entity) throws Exception {
		super.remove(entity);
	}

	@Override
	public List<Portfolio> retrieveAll() throws Exception {
		return super.retrieveAll();
	}

	@Override
	public Portfolio retrieveById(Object id) throws Exception {
		return super.retrieveById(id);
	}

	public Portfolio retrieveByAsset(Asset asset) throws Exception {
		return dao.retrieveByAsset(asset);
	}
	
	@Override
	public Portfolio update(Portfolio entity) throws Exception {
		return super.update(entity);
	}

	@Override
	public void validateBussinessRules(Portfolio entity, boolean isUpdate) {
		// TODO Auto-generated method stub
	}

	@Override
	public void validateInvalidFields(Portfolio entity, boolean isUpdate) {
		// TODO Auto-generated method stub
	}

	@Override
	public void validateRequiredFields(Portfolio entity, boolean isUpdate) {
		// TODO Auto-generated method stub
	}

	public void updatePortfolio() throws Exception {
		dao.removeAll();
		List<Trade> trades = dao.getTrades();
		
		Map<Asset, Portfolio> map = new HashMap<Asset, Portfolio>();
		for(Trade t: trades){
			Portfolio portfolioTrade = map.get(t.getAsset());
			if(portfolioTrade == null){
				portfolioTrade = new Portfolio();
				portfolioTrade.setQuantity(0);
				portfolioTrade.setAveragePrice(0d);
				portfolioTrade.setAsset(t.getAsset());
				map.put(t.getAsset(), portfolioTrade);
			}
			if(t.getType().equals(Trade.TYPE_BUY)){
				portfolioTrade.setAveragePrice(BussinessUtils.getPortfolioPrice(portfolioTrade, t));
				portfolioTrade.setQuantity(portfolioTrade.getQuantity() + t.getQuantity());
			} else {
				portfolioTrade.setQuantity(portfolioTrade.getQuantity() - t.getQuantity());
			}
		}
		
		for(Portfolio portfolio: map.values()){
			if(portfolio.getQuantity() > 0)
				insert(portfolio);
		}
	}
	
	
}
